import XRegExp from 'xregexp';

export const restoreInitialData = (data: string) => {
  return restoreCodeBlockData(data);
};

const restoreCodeBlockData = (data: string) => {
  return XRegExp.replace(
    data,
    XRegExp(/<pre.*?><code.*?>([\s\S]*?)<\/code><\/pre>/gm),
    (...args) => {
      const args1 = typeof args[1] === 'string' ? args[1] : '// nodata';
      const match = XRegExp.matchChain(args1, [
        {
          regex: XRegExp(/<li.*?>(?:<div.*?>.*?<\/div>)?(.*?)<\/li>/gm),
          backref: 1,
        },
      ]).join('\n');
      return match.trim() ? args[0].replace(args1, match) : (args[0] as any);
    },
    'all',
  ).replaceAll(
    '<div class="yw-code-copy position-absolute bg-body-secondary rounded-2 top-0 m-2"><i class="yw-code-copy-btn cursor-pointer bi bi-clipboard fs-5 px-2 py-1 d-block"></i></div>',
    '',
  );
};
